<template>
  <div class="area-picker-container">
    <!-- 触发按钮 -->
    <div class="selected-area" @click="showPicker = true">
      <span v-if="selectedProvince">
        {{ selectedProvince }} {{ selectedCity }} {{ selectedDistrict }}
      </span>
      <span v-else class="placeholder">请选择地区</span>
    </div>

    <!-- 选择器弹窗 -->
    <div class="picker-mask" v-if="showPicker" @click="hidePicker"></div>
    <div class="picker-panel" v-if="showPicker">
      <!-- 顶部操作栏 -->
      <div class="picker-header">
        <button class="picker-btn cancel" @click="hidePicker">取消</button>
        <h3 class="picker-title">选择地区</h3>
        <button class="picker-btn confirm" @click="confirmSelection">确认</button>
      </div>

      <!-- 滚动选择区域 -->
      <div class="picker-content">
        <div class="picker-col" ref="provinceCol">
          <ul @touchstart="onTouchStart('province')" @touchmove="onTouchMove('province')"
            @touchend="onTouchEnd('province')">
            <li v-for="(item, index) in provinces" :key="index" :class="{ active: index === provinceIndex }">{{
              item.name }}</li>
          </ul>
        </div>
        <div class="picker-col" ref="cityCol">
          <ul @touchstart="onTouchStart('city')" @touchmove="onTouchMove('city')" @touchend="onTouchEnd('city')">
            <li v-for="(item, index) in cities" :key="index" :class="{ active: index === cityIndex }">{{ item.name }}
            </li>
          </ul>
        </div>
        <div class="picker-col" ref="districtCol">
          <ul @touchstart="onTouchMove('district')" @touchmove="onTouchMove('district')"
            @touchend="onTouchEnd('district')">
            <li v-for="(item, index) in districts" :key="index" :class="{ active: index === districtIndex }">{{
              item.name }}</li>
          </ul>
        </div>
      </div>

      <!-- 选中指示器 -->
      <div class="picker-indicator"></div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 显示控制
      showPicker: false,

      // 选中值
      selectedProvince: '',
      selectedCity: '',
      selectedDistrict: '',

      // 索引控制
      provinceIndex: 0,
      cityIndex: 0,
      districtIndex: 0,

      // 滚动状态
      touchState: {
        province: {
          startY: 0,
          moveY: 0,
          currentY: 0,
          isMoving: false,
          itemHeight: 44 // 每个选项的高度
        },
        city: {
          startY: 0,
          moveY: 0,
          currentY: 0,
          isMoving: false,
          itemHeight: 44
        },
        district: {
          startY: 0,
          moveY: 0,
          currentY: 0,
          isMoving: false,
          itemHeight: 44
        }
      },

      // 地区数据 - 简化版示例
      areaData: [
        {
          name: '北京市',
          cities: [
            {
              name: '北京市',
              districts: ['东城区', '西城区', '朝阳区', '丰台区', '石景山区', '海淀区', '顺义区']
            }
          ]
        },
        {
          name: '上海市',
          cities: [
            {
              name: '上海市',
              districts: ['黄浦区', '徐汇区', '长宁区', '静安区', '普陀区', '虹口区', '杨浦区']
            }
          ]
        },
        {
          name: '广东省',
          cities: [
            {
              name: '广州市',
              districts: ['越秀区', '海珠区', '荔湾区', '天河区', '白云区', '黄埔区', '番禺区']
            },
            {
              name: '深圳市',
              districts: ['福田区', '罗湖区', '南山区', '宝安区', '龙岗区', '盐田区']
            },
            {
              name: '佛山市',
              districts: ['禅城区', '南海区', '顺德区', '三水区', '高明区']
            }
          ]
        }
        // 可以继续添加其他省份数据
      ]
    };
  },

  computed: {
    // 省份列表
    provinces() {
      return this.areaData;
    },

    // 根据选中的省份获取城市列表
    cities() {
      if (this.provinces.length && this.provinceIndex >= 0) {
        return this.provinces[this.provinceIndex].cities || [];
      }
      return [];
    },

    // 根据选中的城市获取区县列表
    districts() {
      if (this.cities.length && this.cityIndex >= 0) {
        return this.cities[this.cityIndex].districts || [];
      }
      return [];
    }
  },

  watch: {
    // 监听省份变化，重置城市和区县索引
    provinceIndex(newVal) {
      this.cityIndex = 0;
      this.districtIndex = 0;
      this.updateScrollPosition('city');
      this.updateScrollPosition('district');
    },

    // 监听城市变化，重置区县索引
    cityIndex(newVal) {
      this.districtIndex = 0;
      this.updateScrollPosition('district');
    }
  },

  mounted() {
    // 初始化滚动位置
    this.updateScrollPosition('province');
    this.updateScrollPosition('city');
    this.updateScrollPosition('district');
  },

  methods: {
    // 显示选择器
    showPicker() {
      this.showPicker = true;
      // 记录当前选中值，用于取消时恢复
      this.tempProvince = this.selectedProvince;
      this.tempCity = this.selectedCity;
      this.tempDistrict = this.selectedDistrict;
    },

    // 隐藏选择器
    hidePicker() {
      this.showPicker = false;
      // 恢复选中值
      this.selectedProvince = this.tempProvince;
      this.selectedCity = this.tempCity;
      this.selectedDistrict = this.tempDistrict;
    },

    // 确认选择
    confirmSelection() {
      this.selectedProvince = this.provinces[this.provinceIndex]?.name || '';
      this.selectedCity = this.cities[this.cityIndex]?.name || '';
      this.selectedDistrict = this.districts[this.districtIndex] || '';
      this.showPicker = false;

      // 触发自定义事件，传递选中结果
      this.$emit('select', {
        province: this.selectedProvince,
        city: this.selectedCity,
        district: this.selectedDistrict
      });
    },

    // 触摸开始
    onTouchStart(type, e) {
      e.preventDefault();
      this.touchState[type].startY = e.touches[0].clientY;
      this.touchState[type].isMoving = true;
    },

    // 触摸移动
    onTouchMove(type, e) {
      e.preventDefault();
      if (!this.touchState[type].isMoving) return;

      const currentY = e.touches[0].clientY;
      this.touchState[type].moveY = currentY - this.touchState[type].startY;

      // 计算新的位置并应用
      const element = this.$refs[`${type}Col`].querySelector('ul');
      const newY = this.touchState[type].currentY + this.touchState[type].moveY;

      // 限制滚动范围
      const maxScroll = 0;
      const minScroll = -(element.children.length - 1) * this.touchState[type].itemHeight;
      const limitedY = Math.max(Math.min(newY, maxScroll), minScroll);

      element.style.transform = `translateY(${limitedY}px)`;
    },

    // 触摸结束
    onTouchEnd(type) {
      if (!this.touchState[type].isMoving) return;

      const element = this.$refs[`${type}Col`].querySelector('ul');
      const finalY = this.touchState[type].currentY + this.touchState[type].moveY;

      // 计算最终应该停留的位置
      const itemHeight = this.touchState[type].itemHeight;
      let index = Math.round(-finalY / itemHeight);

      // 限制索引范围
      const maxIndex = this[`${type}s`].length - 1;
      index = Math.max(0, Math.min(index, maxIndex));

      // 更新位置和索引
      const newY = -index * itemHeight;
      element.style.transform = `translateY(${newY}px)`;
      this[`${type}Index`] = index;

      // 保存当前位置状态
      this.touchState[type].currentY = newY;
      this.touchState[type].isMoving = false;
      this.touchState[type].moveY = 0;
    },

    // 更新滚动位置
    updateScrollPosition(type) {
      const element = this.$refs[`${type}Col`]?.querySelector('ul');
      if (!element) return;

      const index = this[`${type}Index`];
      const newY = -index * this.touchState[type].itemHeight;

      element.style.transform = `translateY(${newY}px)`;
      this.touchState[type].currentY = newY;
    }
  }
};
</script>

<style scoped>
/* 触发按钮样式 */
.selected-area {
  width: 100%;
  padding: 12px 15px;
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  font-size: 16px;
  color: #333;
  text-align: left;
}

.placeholder {
  color: #999;
}

/* 遮罩层 */
.picker-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 1000;
}

/* 选择器面板 */
.picker-panel {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  border-radius: 16px 16px 0 0;
  z-index: 1001;
}

/* 头部样式 */
.picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.picker-btn {
  padding: 8px 15px;
  background: none;
  border: none;
  font-size: 16px;
  cursor: pointer;
}

.cancel {
  color: #999;
}

.confirm {
  color: #1677ff;
}

.picker-title {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

/* 内容区域 */
.picker-content {
  display: flex;
  height: 260px;
  overflow: hidden;
  position: relative;
}

.picker-col {
  flex: 1;
  height: 100%;
  overflow: hidden;
  position: relative;
}

.picker-col ul {
  list-style: none;
  padding: 0;
  margin: 0;
  transition: transform 0.1s ease-out;
  text-align: center;
  padding-top: 110px;
  /* 中间选中区域的位置 */
  padding-bottom: 110px;
}

.picker-col li {
  height: 44px;
  line-height: 44px;
  font-size: 16px;
  color: #999;
}

.picker-col li.active {
  color: #333;
  font-weight: 500;
}

/* 选中指示器 */
.picker-indicator {
  position: absolute;
  top: 110px;
  left: 0;
  right: 0;
  height: 44px;
  pointer-events: none;
  box-sizing: border-box;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}
</style>
